import { useState, useEffect, useContext, useRef } from 'react';
import { NavBar, List, Input, Radio, Toast } from 'antd-mobile';

import { MySdkStoreContext } from '../../context';

import './style.scss';

export default function({ onClose, onOk }) {
  const mySdkStore = useContext(MySdkStoreContext);
  const inputRef = useRef();
  // 标签列表
  const [list, setList] = useState([]);
  // 已选中的标签
  const [seletedItem, setSeletedItem] = useState();

  // 获取标签列表
  const getList = async () => {
    const res = await mySdkStore.sdk.queryFavoriteTags();
    setList(res);
  }

  useEffect(() => {
    getList();
  }, []);

  // 新增新标签事件
  const handleAddLabel = async () => {
    const tagName = inputRef.current.nativeElement.value;
    if (tagName) {
      await mySdkStore.sdk.addOrUpdateFavoriteTag({ tagName });
      Toast.show('标签已新增');
      inputRef.current.clear();
      getList();
    }
  }

  // 选择完成后，点击”保存“按钮事件
  const handleCollect = async () => {
    const allTagInfos = list.filter(item => seletedItem.indexOf(item.code) > -1);
    onOk([seletedItem], allTagInfos);
  }

  return (<div className="userLabelPage">
    <NavBar
      onBack={onClose} style={{ background: '#fff', border: 'none' }}
      right={[<a key="save" onClick={handleCollect}>保存</a>]}
    >我的群组</NavBar>
    <List style={{ '--border-top': 0, '--border-bottom': 0, marginTop: 12 }}>
      <List.Item>
        <Input ref={inputRef} placeholder="请输入新标签" onBlur={handleAddLabel} maxLength={10} />
      </List.Item>
    </List>
    <Radio.Group value={seletedItem} onChange={val => setSeletedItem(val)}>
    <List style={{ margin: '12px 0 20px'}} header="从现有标签中选择">
      { list.map(item =>
        <List.Item key={item.code}>
          <div>
            <Radio style={{ marginRight: 8 }} value={item.code} />
            { item.name }
          </div>
        </List.Item>
      )}
    </List>
    </Radio.Group>
  </div>)
}